import { createRouter, createWebHashHistory } from "vue-router";
import routes from "./index";
import { getStore } from "@/utils/store";
import { Notify } from "vant";

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  const meta = to.meta;
  const token = getStore({ name: "token" });
  const userInfo = getStore({ name: "userInfo" });
  if (token) {
    if (to.path === "/login" && userInfo) {
      next({ path: "/" });
    } else if (to.path === "/login" && !userInfo) {
      console.log("未找到用户信息，请重新登入！");
      Notify({
        type: "danger",
        duration: 1000,
        message: "未找到用户信息，请重新登入！",
      });
      next();
    } else if (!userInfo) {
      next("/login");
    } else {
      next();
    }
  } else {
    if (to.path === "/login") {
      next();
    } else {
      //判断是否需要认证，没有登录访问去登录页
      if (meta.isAuth === false) {
        next();
      } else {
        Notify({
          type: "warning",
          duration: 1000,
          message: "你暂未登入或登入已过期！",
        });
        next({ path: "/login" });
      }
    }
  }
});

router.afterEach((to, from) => {
  // 处理动画
  if (to.meta.index > from.meta.index) {
    to.meta.transition = "Skleft";
    from.meta.transition = "Skleft";
  } else if (to.meta.index < from.meta.index) {
    to.meta.transition = "Skright";
    from.meta.transition = "Skright";
  } else {
    to.meta.transition = "Skcenter";
    from.meta.transition = "Skcenter";
  }
});

export default router;
